package com.chat.xx.config.webSocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: xiongz
 * @time: 2020/7/13 9:36
 */
@Slf4j
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与{}客户端建立连接，通道开启！",ctx.name());
        //添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与{}客户端断开连接，通道关闭！",ctx.name());
        //从channelGroup通道组删除
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //接收的消息
        log.info("收到客户端{}的数据：{}" ,ctx.channel().id(), msg.text());
        // 单独发消息
//         sendMessage(ctx,"单独发送的消息");
        // 群发消息
//        sendAllMessage("群发消息");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Channel channel = ctx.channel();
        if(channel.isActive())ctx.close();
    }

    public static void sendMessage(ChannelHandlerContext ctx, String message){
        ChannelFuture channelFuture = ctx.writeAndFlush(new TextWebSocketFrame(message));
    }

    public static void sendAllMessage(String message){
        log.info("websocket消息推送:======"+message);
        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
    }
}
